let roomProto         = require('../../API/RoomProto');
let gameProto         = require('./PDKProto');
let roomAPI           = require('../../API/RoomAPI');
let gameLogic         = require('./PDKGameLogic');
let enumeration       = require('../../Constant/enumeration');
var RoomMessageRouter = 'game.gameHandler.roomMessageNotify';
var GameMessageRouter = 'game.gameHandler.gameMessageNotify';

cc.Class({
    extends: cc.Component,

    properties: {
		bureauLabel: cc.Label,
        handCardWidgetCtrl: require('PDKHandCradWidgetCtrl'),
        operationBtnWidgetCtrl: require('PDKOperationBtnWdigetCtrl'),
        cardCountLabelArr: [cc.Label],
        showTipNodeArr: [cc.Node],
        showOutCardNodeArr: [cc.Node],
        clockPosNodeArr: [cc.Node],
        alertAnimationNodeArr: [cc.Node],
        showHandCardNode: [cc.Node],
        nicknameLabelArr: [cc.Label],
		offlineNodeArr: [cc.Node],
		msgTextNodeArr: [cc.Node],
        goldLabelArr: [cc.Label],
        userIconSpriteArr: [cc.Sprite],
        showOutCardWidgetPrefab: cc.Prefab,
        showHandCardWidgetPrefab: cc.Prefab,
        clockWidgetPrefab: cc.Prefab,

        cardNode: cc.Node,
        shunziAnimationPrefab: cc.Prefab,
        zhandanAnimationPrefab: cc.Prefab,
        animationNode: cc.Node,

        roomIDLabel: cc.Label,

        nextWarnTipNode: cc.Node,

        winScoreLabelArr: [cc.Label],
        loseScoreLabelArr: [cc.Label],
		chatAnim:          cc.Prefab,
		chuntianPrefab:    cc.Prefab,
    },

    onLoad: function () {
        this.gameInited = false;

        this.myChairID = -1;
        this.roomID = "";

        this.handCardWidgetCtrl.initWidget();

        this.turnCardDataArr = [];

        this.roomUserInfoArr = [null, null, null];


        Global.MessageCallback.addListener('RoomMessagePush', this);
        Global.MessageCallback.addListener('GameMessagePush', this);
        Global.MessageCallback.addListener('ReConnectSuccess', this);
        Global.MessageCallback.addListener('GAME_EVENT', this);
        Global.MessageCallback.addListener('UpdateGameBg', this);
		Global.MessageCallback.addListener('UpdateGameCardBg', this);
        
        // 获取场景
        this.scheduleOnce(function () {
            roomAPI.roomMessageNotify(roomProto.getRoomSceneInfoNotify());
        }, 0.2);

		this.updateBgSprite();
		this.updateCard0Node();
		if (cc.sys.localStorage.getItem('gameMusic') == "gameMusic2") {
			Global.AudioManager.startPlayBgMusic("Game/Common/Audio/game_bg_2");
		}
		else {
			Global.AudioManager.startPlayBgMusic("Game/Common/Audio/game_bg_1");
		}
    },

	updateCard0Node: function () {
		let cardbg = cc.sys.localStorage.getItem('cardBg');
		let url = 'Game/Common/card_back_0';
		if (cardbg == 'cardBg1') {
			url = 'Game/Common/card_back_0';
		}
		else if (cardbg == 'cardBg2') {
			url = 'Game/Common/card_back_1';
		}
		else if (cardbg == 'cardBg3') {
			url = 'Game/Common/card_back_2';
		}
		else if (cardbg == 'cardBg4') {
			url = 'Game/Common/card_back_3';
		}
		Global.CCHelper.updateSpriteFrame(url, this.cardNode.getComponent(cc.Sprite));
		let rightCardCount = cc.find('Head2/rightCardCount', this.node);
		Global.CCHelper.updateSpriteFrame(url, rightCardCount.getComponent(cc.Sprite));
		let leftCardCount = cc.find('Head3/leftCardCount', this.node);
		Global.CCHelper.updateSpriteFrame(url, leftCardCount.getComponent(cc.Sprite));
	},

    onDestroy: function () {
        Global.MessageCallback.removeListener('RoomMessagePush', this);
        Global.MessageCallback.removeListener('GameMessagePush', this);
        Global.MessageCallback.removeListener('ReConnectSuccess', this);
        Global.MessageCallback.removeListener('GAME_EVENT', this);
        Global.MessageCallback.removeListener('UpdateGameBg', this);
		Global.MessageCallback.removeListener('UpdateGameCardBg', this);
    },

	enterHall: function () {
		if(!this.gameInited) return;
		Global.DialogManager.destroyDialog('Game/PaoDeKuai/PDKMainDialog');
		if (this.roomCreatorInfo && this.roomCreatorInfo.creatorType == Global.Enum.roomCreatorType.UNION_CREATE) {
			Global.DialogManager.createDialog("UI/Union/UnionMain/UnionMainDialog", {unionID: this.roomCreatorInfo.unionID});
		}
		else {
			Global.DialogManager.createDialog('UI/Hall/HallDialog', null, function () {
				if (Global.DialogManager.isDialogExit('Game/PaoDeKuai/PDKResultDialog')) {
					Global.DialogManager.destroyDialog('Game/PaoDeKuai/PDKResultDialog');
				}
			}.bind(this));
		}
	},

    messageCallbackHandler: function(router, msg) {
        if(router === 'RoomMessagePush') {
            if(msg.type === roomProto.USER_LEAVE_ROOM_RESPONSE) {
                if(msg.data.chairID === this.myChairID) {
                    Global.DialogManager.removeLoadingCircle();
                }
            }
			else if(msg.type === roomProto.OTHER_USER_ENTRY_ROOM_PUSH) {
                if(!this.gameInited) return;
                // 设置信息
                this.onUserEntryRoom(msg.data.roomUserInfo);
				this.verifyZuobi(msg.data.roomUserInfo);
            }
			else if(msg.type === roomProto.USER_LEAVE_ROOM_PUSH) {
                if(!this.gameInited) return;
                // 删除用户信息
                this.onUserLeaveRoom(msg.data.roomUserInfo);
            }
			else if(msg.type === roomProto.USER_READY_PUSH) {
                if(!this.gameInited) return;
                // 用户准备
                this.onUserReady(msg.data.chairID);
            }
			else if(msg.type === roomProto.GET_ROOM_SCENE_INFO_PUSH){
                this.roomIDLabel.string = "房号：" + msg.data.roomID;
				this.roomID = msg.data.roomID;
                this.gameInit(msg.data.roomUserInfoArr, msg.data.gameData, msg.data.gameRule);
				this.roomCreatorInfo = msg.data.roomCreatorInfo;
				if (msg.data.gameRule.maxPlayerCount == 2) {
					this.setTwoPlayerHeadPos();
				}
				if (msg.data.gameData.firstChairID != null) {
					this.setBanker(msg.data.gameData.firstChairID);
				}
            }
			else if (msg.type === roomProto.ROOM_USER_INFO_CHANGE_PUSH){
				if(!this.gameInited) return;
                for (let i = 0; i < this.roomUserInfoArr.length; ++i){
                    if (this.roomUserInfoArr[i] && this.roomUserInfoArr[i].userInfo.uid === msg.data.changeInfo.uid){
                        this.roomUserInfoArr[i].userInfo = msg.data.changeInfo;
                        break;
                    }
                }
				// if (this.curBureau == this.gameRule.bureau) {
					this.updateUserInfo();
				// }
            }
			else if(msg.type === roomProto.ROOM_DISMISS_PUSH) {
				this.askForExitArr = null;
				this.roomDismissReason = msg.data.reason;
			}
			else if(msg.type === roomProto.ASK_FOR_DISMISS_PUSH) {
				this.askForExitArr = msg.data.chairIDArr;
				if (msg.data.chairIDArr.indexOf(false) != -1) {
					this.askForExitArr = null;
				}
				if (!Global.DialogManager.isDialogExit('Game/DismissNode')) {
					msg.data.myChairID = this.myChairID;
					Global.DialogManager.createDialog('Game/DismissNode', msg.data, function (dialog) {
						Global.DialogManager.removeLoadingCircle();
					});
				}
			}
			else if(msg.type === roomProto.USER_CHAT_PUSH) {
				this.onChat(msg.data.fromChairID, msg.data.toChairID, msg.data.msg);
			}
			else if(msg.type == roomProto.USER_OFF_LINE_PUSH){
				let index = this.getUserChairIndex(msg.data.chairID);
				this.offlineNodeArr[index].active = true;
			}
		} else if(router === 'GameMessagePush') {
			if (!this.gameInited) return;
			if(msg.type === gameProto.GAME_START_PUSH) {
				this.gameStarted = true;
				this.curBureau = msg.data.curBureau;
				this.bureauLabel.string = '局数：'+msg.data.curBureau+'/'+this.gameRule.bureau;
				this.onGameStart(msg.data.curChairID, msg.data.selfCardArr);
				this.isFirstTurnArray = [true, true, true];
			} 
			else if(msg.type === gameProto.GAME_USER_OUT_CARD_PUSH) {
				this.isFirstTurnArray[msg.data.chairID] = false;
				this.onUserOutCard(msg.data.chairID, msg.data.outCardArr, msg.data.curChairID, msg.data.leftCardCount, msg.data.enablePass, msg.data.handCardArr);
			} 
			else if(msg.type === gameProto.GAME_USER_PASS_PUSH) {
				this.isFirstTurnArray[msg.data.chairID] = false;
				this.onUserPass(msg.data.chairID, msg.data.curChairID, msg.data.isNewTurn, msg.data.enablePass, msg.data.handCardArr);
			}
			else if(msg.type === gameProto.GAME_RESULT_PUSH){
				this.onGameResult(msg.data);
			} 
			else if (msg.type === gameProto.GAME_USER_BOMB_WIN_PUSH){
				this.onUserBombWin(msg.data.chairID, true);
			}
			else if (msg.type === gameProto.GAME_CHAT_PUSH){
				this.onGameChat(msg.data.chairID, msg.data.type, msg.data.msg);
			}
			else if(msg.type == gameProto.GAME_DISMISS_PUSH) {
				if (msg.data.userArray) {
					msg.data.isUnionCreate = true;
					if (this.roomCreatorInfo && this.roomCreatorInfo.creatorType == Global.Enum.roomCreatorType.USER_CREATE) {
						msg.data.isUnionCreate = false;
					}
					msg.data.isBureauFull = (this.curBureau == this.gameRule.bureau);
					msg.data.enterHall = this.enterHall.bind(this);
					msg.data.roomDismissReason = msg.data.reason;
					msg.data.myChairID = this.myChairID;
					this.showPDKAllResultFuc = () => {
						this.showPDKAllResultFuc = null;
						Global.DialogManager.createDialog('Game/PaoDeKuai/PDKAllResult', msg.data, function (dialog) {
							Global.DialogManager.removeLoadingCircle();
						});
					};
					if (msg.data.reason != enumeration.gameRoomDismissReason.BUREAU_FINISHED) { // 手动解散，直接显示总决算觉面 
						this.showPDKAllResultFuc();
					}
				}
				else {
					this.enterHall();
				}
			}
			else if(msg.type == gameProto.GAME_TRUST_PUSH) {
				if (msg.data.chairID == this.myChairID) {
					cc.find('Tuoguan', this.node).active = msg.data.trust;
				}
			}
			else if(msg.type == gameProto.GAME_PRETURN_CARDS_PUSH) {
				let logic = cc.find('PreTurnCards', this.node).getComponent('PDKPreTurnCards');
				logic.init(msg.data.list);
			}
		} 
		else if(router === 'ReConnectSuccess' || (router == 'GAME_EVENT' && msg == cc.game.EVENT_SHOW)) {
			if(Global.UserModel.isInRoom()) {
				Global.API.hall.joinRoomRequest(this.roomID, function() {
					this.gameInited = false;
					roomAPI.roomMessageNotify(roomProto.getRoomSceneInfoNotify());
				}.bind(this), function () {
					// Global.DialogManager.destroyDialog('Game/PaoDeKuai/PDKMainDialog');
					this.enterHall();
				}.bind(this));
			} else {
				// Global.DialogManager.destroyDialog('Game/PaoDeKuai/PDKMainDialog');
				this.enterHall();
			}
		}
		else if(router == 'UpdateGameBg') {
			this.updateBgSprite();
		}
		else if(router == 'UpdateGameCardBg') {
			this.updateCard0Node();
		}
	},

	updateBgSprite: function () {
		let bgUrl = cc.sys.localStorage.getItem('gameBg');
		let title = (!bgUrl || bgUrl == 'gameBg1')? 'Game/PaoDeKuai/paodekuaidiwen':'Game/PaoDeKuai/paodekuaidiwen1';
		bgUrl = (!bgUrl || bgUrl == 'gameBg1')? 'Game/Common/beijinglan':'Game/Common/beijinglv';
		Global.CCHelper.updateSpriteFrame(title, cc.find('background/diwen', this.node).getComponent(cc.Sprite));
		Global.CCHelper.updateSpriteFrame(bgUrl, cc.find('background', this.node).getComponent(cc.Sprite));
	},

	onBtnClick: function (event, parameter) {
		if (!this.gameInited) return;
		Global.AudioManager.playCommonSoundClickButton();
		if (parameter === 'ready'){
			/* this.resetGame(); */
			roomAPI.roomMessageNotify(roomProto.userReadyNotify());
		} 
		else if (parameter === 'pass'){
			// this.selfOutCardCallback(null); 
		} 
		else if (parameter === 'tip'){
			if (!!this.turnCardDataArr && this.turnCardDataArr.length > 0){
				if (!this.handCardWidgetCtrl.searchOutCard(this.turnCardDataArr, this.gameRule)){
					this.selfOutCardCallback(null); 
				}
			}
		}
		else if (parameter === 'outCard'){
			let selectedCardDataArr = this.handCardWidgetCtrl.getSelectedCard();
			// 下家报单，出单排的时候判定
			let nextBaodan = false;
			if (this.gameRule.maxPlayerCount == 3 && parseInt(this.cardCountLabelArr[1].string) === 1 && selectedCardDataArr.length === 1) {
				nextBaodan = true;
			}
			else if (this.gameRule.maxPlayerCount == 2 && (parseInt(this.cardCountLabelArr[1].string) === 1 || parseInt(this.cardCountLabelArr[2].string) === 1) && selectedCardDataArr.length === 1) {
				nextBaodan = true;
			}
			if (nextBaodan) { // 必须出最大牌
				let allCardDataArr = this.handCardWidgetCtrl.getAllCard();
				let outCardLogicValue = gameLogic.getCardLogicValue(selectedCardDataArr[0]);
				for (let i = 0; i < allCardDataArr.length; ++i){
					if (gameLogic.getCardLogicValue(allCardDataArr[i]) > outCardLogicValue){
						Global.DialogManager.addTipDialog("下家已经报单，单排必须出最大牌");
						return;
					}
				}
			}
			this.selfOutCardCallback(selectedCardDataArr);
		}
		else if (parameter === 'exit'){
			if (!this.gameStarted) {
				Global.DialogManager.addPopDialog('确认退出游戏?', function() {
					Global.NetworkManager.notify(RoomMessageRouter, roomProto.userLeaveRoomNotify());
					Global.DialogManager.addLoadingCircle();
				}, function() {});
			}
			else {
				Global.DialogManager.addPopDialog('是否确定发出解散申请？', function() {
					Global.NetworkManager.notify(RoomMessageRouter, roomProto.getAskForDismissNotifyData(true));
					Global.DialogManager.addLoadingCircle();
				}, function() {});
			} 
		} 
		else if (parameter === 'settings'){
			Global.DialogManager.createDialog('Setting/SettingDialog');
		}
		else if (parameter === 'rule'){
			Global.DialogManager.createDialog("GameCommon/GameRule/GameRuleDialog", { kind: Global.Enum.gameType.PDK });
		}
	},

	getRoomData: function () {
		var msg = {
			gameRule: this.gameRule,
			bureau: this.bureauLabel.string,
			handCards: this.handCardWidgetCtrl.getAllCard(),
			roomUserInfoArr: this.roomUserInfoArr,
			roomCreatorInfo: this.roomCreatorInfo,
		};
		return msg;
	},

    gameInit: function (roomUserInfoArr, gameData, gameRule) {
		this.askForExitArr = null;
		this.resetGame();
		for (let user of roomUserInfoArr) {
			this.roomUserInfoArr[user.chairID] = user;
		}
        this.gameInited = true;
		this.gameStarted = gameData.gameStarted;
		this.gameRule = gameRule;
		this.curBureau = gameData.curBureau;
		this.isFirstTurnArray = gameData.isFirstTurnArray;
		this.bureauLabel.string = '局数：'+gameData.curBureau+'/'+this.gameRule.bureau;
		this.cardCountLabelArr[1].node.active = this.gameRule.showCardsCount;
		this.cardCountLabelArr[2].node.active = this.gameRule.showCardsCount;
        // 获取自己的位置
        for (let i = 0; i < roomUserInfoArr.length; ++i){
            let roomUserInfo = roomUserInfoArr[i];
            if (roomUserInfo.userInfo.uid === Global.UserModel.uid){
                this.myChairID = roomUserInfo.chairID;
                break;
            }
        }
        // 设置用户信息
        for (let i = 0; i < roomUserInfoArr.length; ++i){
            this.onUserEntryRoom(roomUserInfoArr[i]);
        }
		this.verifyZuobi(roomUserInfoArr[this.myChairID]);
        // 未开局状态
        if(gameData.gameStatus === gameProto.gameStatus.NONE){
			if (gameData.curBureau == 0) {
				/* cc.find('copy', this.node).active = true;
				cc.find('invite', this.node).active = true; */
				cc.find('backhall', this.node).active = true;
			}
			for (let user of roomUserInfoArr) {
				if ((user.userStatus&roomProto.userStatusEnum.READY) > 0) {
					this.onUserReady(user.chairID);
				}
				else {
					if (user.chairID == this.myChairID && this.curBureau < this.gameRule.bureau) {
						cc.find('ready', this.node).active = true;
					}
				}
			}
        } 
		else if (gameData.gameStatus === gameProto.gameStatus.OUT_CARD){
            // 设置手牌
            this.handCardWidgetCtrl.onSendCard(gameData.selfCardArr, false);
            this.handCardWidgetCtrl.startGame();
            // 设置其他玩家手牌数
            for (let i = 0; i < 3; ++i){
                // 设置其他玩家手牌数
                this.updateCardCount(i, gameData.allUserCardCountArr[i]);
                let index = this.getUserChairIndex(i);
                // 设置是否需要显示警告
                if (gameData.allUserCardCountArr[i].length === 1) this.alertAnimationNodeArr[index].active = true;
            }
            // 更新炸弹分数变化
            for (let i = 0; i < gameData.userBombTimes.length; ++i){
                let times = gameData.userBombTimes[i];
                for (let j = 0; j < times; ++j){
                    this.onUserBombWin(i, false);
                }
            }
            // 不是新的一轮则记录上一轮出牌
            this.turnCardDataArr = gameData.turnCardDataArr;
            // 如果是自己出牌，则显示出牌按钮
            if(gameData.curChairID === this.myChairID){
                this.operationBtnWidgetCtrl.startOutCard(gameData.curChairID === gameData.turnWinerChairID, gameData.enablePass, this.gameRule.bichu);
            }
            // 设置定时器
            this.showClock(gameData.curChairID, this.autoOutCard.bind(this));
        }
		cc.find('Tuoguan', this.node).active = gameData.userTrustArray[this.myChairID];
		cc.find('Setting/Layout/TuoButton', this.node).active = true;
		cc.find('Voice', this.node).active = this.gameRule.yuyin;
		
		for (let i = 1; i <= 3; ++i) {
			let node = cc.find('Head'+i+'/msgbg', this.node);
			this.addHeadClickEvent(node, i-1);
		}
    },

	addHeadClickEvent: function (node, index) {
		node.on(cc.Node.EventType.TOUCH_START, () => {
			if (node.lastClick && Date.now()-node.lastClick < 500) { /* 防止重复点击 */ 
				return;
			}
			node.lastClick = Date.now();
			let toChairID = (index+this.myChairID)%3;
			let user = this.roomUserInfoArr[toChairID];
			let address = null;
			try { address = JSON.parse(user.userInfo.address); } catch(e) {}
			let params = {
				fromChairID: this.myChairID,
				toChairID: toChairID,
				avatar: user.userInfo.avatar,
				id: user.userInfo.uid,
				ip: user.userInfo.lastLoginIP,
				x: address? address.x:'未知',
				y: address? address.y:'未知',
				location: user.userInfo.location,
				gold: user.userInfo.score,
				name: user.userInfo.nickname,
			};
			Global.DialogManager.createDialog('Chat/HeadDetail', params);
		}, this);
	},

    resetGame: function (isRetainReady) {
        // 清除手牌
        this.handCardWidgetCtrl.resetWidget();
        // 清除所有提示
        this.clearState(isRetainReady);
        // 清除所有出牌
        for(let i = 0; i < 3; ++i){
            this.showOutCardNodeArr[i].removeAllChildren();
        }
        // 清除闹钟
        for (let i = 0; i < 3; ++i){
            if (i === 0){
                let node = this.operationBtnWidgetCtrl.getClockNode();
                if(node) node.destroyAllChildren();
            }else{
                this.clockPosNodeArr[i].destroyAllChildren();
            }
        }
        // 清除按钮
        this.operationBtnWidgetCtrl.clearWidget();
        // 隐藏牌数,隐藏警报
        for (let i = 1; i < 3; ++i){
            this.cardCountLabelArr[i].node.parent.active = false;
            this.alertAnimationNodeArr[i].active = false;
        }
        // 清除上轮牌
        this.turnCardDataArr = [];
        // 清楚手牌显示
        for(let i = 0; i < this.showHandCardNode.length; ++i){
            this.showHandCardNode[i].removeAllChildren();
        }
        // 隐藏包赔提示
        this.nextWarnTipNode.active = false;
        // 清除发牌动画
        this.stopSendCardAnimation();
    },

    onReconnection: function () {
        this.resetGame();
        roomAPI.roomMessageNotify(roomProto.getRoomSceneInfoNotify());
    },
    
    onUserEntryRoom: function (roomUserInfo) {
        // 设置用户角色、昵称、金币
        let index = this.getUserChairIndex(roomUserInfo.chairID);
        this.nicknameLabelArr[index].string = Global.UserModel.convertNickname(roomUserInfo.userInfo.nickname);
		this.goldLabelArr[index].string = Math.floor(roomUserInfo.userInfo.score); 
        Global.CCHelper.updateSpriteFrame(roomUserInfo.userInfo.avatar, this.userIconSpriteArr[index]);
        if (index > 0) this.nicknameLabelArr[index].node.parent.active = true;

        if ((roomUserInfo.userStatus & roomProto.userStatusEnum.READY) !== 0 && (roomUserInfo.userStatus & roomProto.userStatusEnum.PLAYING) === 0){
            this.onUserReady(roomUserInfo.chairID);
        }
        this.roomUserInfoArr[roomUserInfo.chairID] = roomUserInfo;
		this.offlineNodeArr[index].active = (roomUserInfo.userStatus&roomProto.userStatusEnum.OFFLINE) > 0;
    },

	verifyZuobi: function (roomUserInfo) {
		if (!this.gameRule.fangzuobi) { return; } 
		if (this.gameRule.maxPlayerCount == 2) { return; }
		if (roomUserInfo.chairID >= this.gameRule.maxPlayerCount) {
			return;
		}
		let add1 = null;
		try { add1 = JSON.parse(roomUserInfo.userInfo.address); } catch(e) {}
		if (!add1) { 
			Global.DialogManager.addPopDialog(`玩家${roomUserInfo.userInfo.nickname}定位未知！`, function() { }); 
			return;
		}
		for (let user of this.roomUserInfoArr) {
			if (!user || user.chairID == roomUserInfo.chairID) { continue; }
			if (user.userInfo.lastLoginIP == roomUserInfo.userInfo.lastLoginIP) {
				Global.DialogManager.addPopDialog(`玩家${roomUserInfo.userInfo.nickname}与玩家${user.userInfo.nickname}IP地址相同！`, function() { }); 
			}
			let add2 = null;
			try { add2 = JSON.parse(user.userInfo.address); } catch(e) {}
			if (!add2) { continue; }
			let distance = Global.Utils.getDistance(add1.x, add1.y, add2.x, add2.y);
			if (distance < 0.1) {  
				Global.DialogManager.addPopDialog(`玩家${roomUserInfo.userInfo.nickname}与玩家${user.userInfo.nickname}距离过近！`, function() { }); 
			}  
		}
	},

    onUserLeaveRoom: function (roomUserInfo) {
        // 删除用户信息
        if(roomUserInfo.chairID === this.myChairID){
            /* this.node.destroy()(); */
			this.enterHall();
        }else{
            let index = this.getUserChairIndex(roomUserInfo.chairID);
            this.nicknameLabelArr[index].node.parent.active = false;

            // 显示准备状态
            this.showTipNodeArr[index].getChildByName('ready').active = false;

            this.roomUserInfoArr[roomUserInfo.chairID] = null;
        }
    },

    updateUserInfo: function () {
        for (let i = 0; i < 3; ++i){
            let roomUserInfo = this.roomUserInfoArr[i];
			if (!!roomUserInfo){
				let index = this.getUserChairIndex(roomUserInfo.chairID);
				this.goldLabelArr[index].string = Math.floor(roomUserInfo.userInfo.score); 
			}
		}
	},

	onUserReady: function (chairID) {
		// 显示准备状态
		let index = this.getUserChairIndex(chairID);
		cc.find('Head' +(index+1)+'/ready', this.node).active = true;
		if (chairID == this.myChairID) {
			cc.find('ready', this.node).active = false;
		}
		if (chairID == this.myChairID) {
			if (Global.DialogManager.isDialogExit('Game/PaoDeKuai/PDKResultDialog')) {
				Global.DialogManager.destroyDialog('Game/PaoDeKuai/PDKResultDialog');
			}
			this.resetGame();
		}
	},

    onGameStart: function (curChairID, selfCardDataArr) {
		this.setBanker(curChairID);
        if (this.handCardWidgetCtrl.getAllCard().length !== 0){
            this.handCardWidgetCtrl.resetWidget();
        }
        // 清除状态
        this.clearState();
        // 开始发牌
		let length = selfCardDataArr.length;
		let cardCount = ((this.gameRule.gameFrameType == gameProto.gameType.CARDS15)? 15:16);
		if (length != cardCount) {
			console.clash("paodekuai cardcount error");
		}
        this.handCardWidgetCtrl.onSendCard(selfCardDataArr, true,function (index) {
            for (let i = 0; i < 3; ++i){
                this.updateCardCount(i, index);
            }
            Global.AudioManager.playSound("Game/PaoDeKuai/Sound/sound_send_card");
            if (index >= length){
                // 显示先手玩家
                // 发牌动画结束后，第一个玩家开始出牌
                this.handCardWidgetCtrl.startGame();
                this.onUserStartOutCard(curChairID, true, false);
                // 停止动画
                this.stopSendCardAnimation();
            }
        }.bind(this));
        // 播放发牌动画
        this.showSendCardAnimation();
        // 显示玩家牌数
        for(let i = 0; i < 3; ++i){
            this.updateCardCount(i, ((this.gameRule.gameFrameType == gameProto.gameType.CARDS15)? 15:16));
        }
		for (let i = 0; i < 3; ++i) {
			cc.find('Head' +(i+1)+'/ready', this.node).active = false;
		}
		cc.find('backhall', this.node).active = false;
    },

    onUserStartOutCard: function (chairID, isNewTurn, enablePass) {
        let index = this.getUserChairIndex(chairID);
        // 设置下一个出牌玩家
        if (chairID === this.myChairID && !enablePass) {
            this.operationBtnWidgetCtrl.startOutCard(isNewTurn, enablePass, this.gameRule.bichu);
        }
		if (chairID === this.myChairID || enablePass) {
			this.showOutCardNodeArr[index].removeAllChildren();
		}
        // 清理自己家的出牌
        let tipsNode = this.showTipNodeArr[index];
        for (let i = 0; i < tipsNode.children.length; ++i){
            tipsNode.children[i].active = false;
        }
        // 开启定时器
		if (!enablePass) {
			this.showClock(chairID, this.autoOutCard.bind(this));
		}
		if (isNewTurn && chairID == this.myChairID) {
			let handCardDataArr = this.handCardWidgetCtrl.getAllCard();
			let cardType = gameLogic.getRestCardsType(handCardDataArr, this.gameRule);
			if ((cardType == gameProto.cardType.THREE_LINE || cardType == gameProto.cardType.THREE_LINE_TAKE_ONE) && this.gameRule.baiwei) {
				return;
			}
			if (!!cardType) {
				let autoCardArr = handCardDataArr.slice();
				this.selfOutCardCallback(autoCardArr);
			}
		}
    },

    selfOutCardCallback: function (cardDataArr) {
        if (!cardDataArr){ // 发送消息
			roomAPI.gameMessageNotify(gameProto.gameUserPassNotify()); 
			this.sendOutPass();
        } 
		else {
            if (cardDataArr.length === 0){ // 提示
                //Global.DialogManager.addTipDialog('出牌错误');
                return;
            }
            // 检查牌是否符合要求
            cardDataArr = gameLogic.sortCardList(cardDataArr);
            let cardType = gameLogic.getCardType(cardDataArr, this.gameRule);
			let handCards = gameLogic.sortCardList(this.handCardWidgetCtrl.getAllCard());
			if (handCards.length == cardDataArr.length) {
				cardType = gameLogic.getRestCardsType(cardDataArr, this.gameRule);
			}
            if (cardType === gameProto.cardType.ERROR){ // 提示
                Global.DialogManager.addTipDialog('出牌不符合规则');
                return;
            }
			let allCardDataArr = this.handCardWidgetCtrl.getAllCard();
			let lastTurn = (allCardDataArr.length == cardDataArr.length);
            if (this.turnCardDataArr.length > 0){
                if (!gameLogic.compareCard(this.turnCardDataArr, cardDataArr, this.gameRule, lastTurn)){ // 提示错误
                    Global.DialogManager.addTipDialog('出牌必须大过上轮');
                    return;
                }
            }
			/* 拆分炸弹检测 */
			if (!this.gameRule.chaizhadan && (cardType != gameProto.cardType.FOUR_LINE_TAKE_X && cardType != gameProto.cardType.BOMB_CARD)) {
				let boomArray = [];
				for (let i = 3; i < handCards.length; ++i) {
					if (gameLogic.getCardValue(handCards[i]) == gameLogic.getCardValue(handCards[i-1]) &&
						gameLogic.getCardValue(handCards[i]) == gameLogic.getCardValue(handCards[i-2]) &&
						gameLogic.getCardValue(handCards[i]) == gameLogic.getCardValue(handCards[i-3])) {
						boomArray.push(gameLogic.getCardValue(handCards[i]));
					}
				}
				if (boomArray.length > 0) {
					for (let card of cardDataArr) {
						if (boomArray.indexOf(gameLogic.getCardValue(card)) != -1) {
							Global.DialogManager.addTipDialog('炸弹不能拆分');
							return;
						}
					}
				}
			}

			/* 摆尾 */
			if (cardType == gameProto.cardType.THREE_LINE || cardType == gameProto.cardType.THREE_LINE_TAKE_ONE) {
				if (!lastTurn || this.gameRule.baiwei) {
					Global.DialogManager.addTipDialog('三张必须带两张牌');
					return;
				}
			}
			/* if (!lastTurn && this.gameRule.baiwei && (cardType == gameProto.cardType.THREE_LINE || cardType == gameProto.cardType.THREE_LINE_TAKE_ONE)) {
				Global.DialogManager.addTipDialog('三张必须带两张牌');
				return;
			} */

			/* 黑桃3必出，没有黑桃3从红桃3以此类推 */
			let isFirstChairID = false;
			let handCount = ((this.gameRule.gameFrameType == gameProto.gameType.CARDS15)? 15:16);
			if (this.cardCountLabelArr[1].string == handCount && this.cardCountLabelArr[2].string == handCount && allCardDataArr.length == handCount) {
				isFirstChairID = true;
			}
			if (this.gameRule.heitao3 && this.curBureau == 1 && isFirstChairID) {
				let card = this.getFirstOutCard(allCardDataArr);
				let color = gameLogic.getCardColor(card)/16;
				color = ['方块', '梅花', '红桃', '黑桃'][color];
				if (cardDataArr.indexOf(card) == -1) {
					Global.DialogManager.addTipDialog('首张牌必出' + color + gameLogic.getCardValue(card));
					return;
				}
			}
            // 出牌
            roomAPI.gameMessageNotify(gameProto.gameUserOutCardNotify(cardDataArr));
			this.sendOutMyCard(cardDataArr);
        }
    },

	onUserOutCard: function (chairID, cardDataArr, curChairID, leftCardCount, enablePass, handCardArr) {
		let index = this.getUserChairIndex(chairID);
		let isPreOperate = true; // 是否提前出牌，预操作 
		if (chairID !== this.myChairID){
			isPreOperate = false;
			this.clockPosNodeArr[index].destroyAllChildren(); // 清除定时器
			this.updateCardCount(chairID, leftCardCount); // 更新玩家手牌数
			if (leftCardCount === 1) { // 设置是否需要显示警告
				this.alertAnimationNodeArr[index].active = true;
				let audio = 'Game/PaoDeKuai/Sound/Man/Man_baojing1';
				let user = this.roomUserInfoArr[chairID];
				if (user && user.userInfo.sex == 1) {
					audio = audio.replace(/Man/, "Woman");
					audio = audio.replace(/Man/, "Woman");
				}
				Global.AudioManager.playSound(audio);
			}
		}
		else {
			let curCardArr = this.handCardWidgetCtrl.getAllCard();
			isPreOperate = (curCardArr.length == handCardArr.length);
			if (isPreOperate) {
				curCardArr.sort((a, b) => a-b);
				handCardArr.sort((a, b) => a-b);
				for (let i = 0; i < curCardArr.length && isPreOperate; ++i) {
					isPreOperate = (curCardArr[i] == handCardArr[i]);
				}
			}
			if (curChairID >= 0){ // 设置下一个出牌玩家
				this.onUserStartOutCard(curChairID, false, enablePass);
			}
			if (!isPreOperate) {
				let clockNode = this.operationBtnWidgetCtrl.getClockNode(); // 停止计时器
				if (!!clockNode){
					clockNode.destroyAllChildren();
				}
				this.operationBtnWidgetCtrl.clearWidget(); // 隐藏按钮
				// this.handCardWidgetCtrl.removeCard(cardDataArr); // 删除牌
				// this.handCardWidgetCtrl.resetSearchOutCardState();
				this.handCardWidgetCtrl.resetWidget();
				this.handCardWidgetCtrl.onSendCard(handCardArr, false);
				this.handCardWidgetCtrl.startGame();
			}
		}
		if (!isPreOperate) {
			this.playOutCardSound(!this.turnCardDataArr || this.turnCardDataArr.length === 0, cardDataArr, chairID); // 播放出牌音效
			this.turnCardDataArr = cardDataArr;
		}
		let node = cc.instantiate(this.showOutCardWidgetPrefab);
		this.showOutCardNodeArr[index].removeAllChildren(); // 显示出牌
		node.parent = this.showOutCardNodeArr[index];
		let ctrl = node.getComponent('PDKShowOutCardWidgetCtrl');
		ctrl.initWidget(cardDataArr, index);
		if (!isPreOperate) {
			this.playOutCardAnimation(cardDataArr, ctrl); // 播放动画
		}
		if (curChairID >= 0){ // 设置下一个出牌玩家
			this.onUserStartOutCard(curChairID, false, enablePass);
		}
	},

	sendOutMyCard: function (cardDataArr) {
		let index = this.getUserChairIndex(this.myChairID);
		let clockNode = this.operationBtnWidgetCtrl.getClockNode(); // 停止计时器
		if (!!clockNode){
			clockNode.destroyAllChildren();
		}
		this.operationBtnWidgetCtrl.clearWidget(); // 隐藏按钮
		this.handCardWidgetCtrl.removeCard(cardDataArr); // 删除牌
		this.handCardWidgetCtrl.resetSearchOutCardState();
		this.playOutCardSound(!this.turnCardDataArr || this.turnCardDataArr.length === 0, cardDataArr, this.myChairID); // 播放出牌音效
		this.turnCardDataArr = cardDataArr;
		let node = cc.instantiate(this.showOutCardWidgetPrefab); // 显示出牌
        this.showOutCardNodeArr[index].removeAllChildren();
		node.parent = this.showOutCardNodeArr[index];
		let ctrl = node.getComponent('PDKShowOutCardWidgetCtrl');
		ctrl.initWidget(cardDataArr, index);
		this.playOutCardAnimation(cardDataArr, ctrl); // 播放动画
	},

	playOutCardSound: function (isFirst, cardDataArr, chairID) {
		let cardType = gameLogic.getCardType(cardDataArr, this.gameRule);
		let audio = "";
		if (cardType === gameProto.cardType.SINGLE){
			let value = gameLogic.getCardValue(cardDataArr[0]);
			audio = "Game/PaoDeKuai/Sound/Man/Man_" + value;
		} 
		else if (cardType === gameProto.cardType.DOUBLE){
			let value = gameLogic.getCardValue(cardDataArr[0]);
			audio = "Game/PaoDeKuai/Sound/Man/Man_dui" + value;
		} 
		else if (cardType === gameProto.cardType.THREE){
			let value = gameLogic.getCardValue(cardDataArr[0]);
			audio ="Game/PaoDeKuai/Sound/Man/Man_tuple" + value;
		} else if (cardType === gameProto.cardType.SINGLE_LINE){
			if (isFirst){
				audio = "Game/PaoDeKuai/Sound/Man/Man_shunzi";
			} else{
				audio = "Game/PaoDeKuai/Sound/Man/Man_dani" + Global.Utils.getRandomNum(1,3);
			}
		} else if (cardType === gameProto.cardType.DOUBLE_LINE){
			if (isFirst){
				audio = "Game/PaoDeKuai/Sound/Man/Man_liandui";
			} else{
				audio = "Game/PaoDeKuai/Sound/Man/Man_dani" + Global.Utils.getRandomNum(1,3);
			}
		} else if (cardType === gameProto.cardType.THREE_LINE){
			if (isFirst){
				audio = "Game/PaoDeKuai/Sound/Man/Man_feiji";
			} else{
				audio = "Game/PaoDeKuai/Sound/Man/Man_dani" + Global.Utils.getRandomNum(1,3);
			}
		} else if (cardType === gameProto.cardType.THREE_LINE_TAKE_ONE){
			if (isFirst){
				if (cardDataArr.length === 4){
					audio = "Game/PaoDeKuai/Sound/Man/Man_sandaiyi";
				}else{
					audio = "Game/PaoDeKuai/Sound/Man/Man_feiji";
				}
			} else{
				audio = "Game/PaoDeKuai/Sound/Man/Man_dani" + Global.Utils.getRandomNum(1,3);
			}
		} else if (cardType === gameProto.cardType.THREE_LINE_TAKE_TWO){
			if (isFirst){
				if (cardDataArr.length === 5){
					audio = "Game/PaoDeKuai/Sound/Man/Man_sandaiyidui";
				}else{
					audio = "Game/PaoDeKuai/Sound/Man/Man_feiji";
				}
			} else{
				audio = "Game/PaoDeKuai/Sound/Man/Man_dani" + Global.Utils.getRandomNum(1,3);
			}
		} else if (cardType === gameProto.cardType.BOMB_CARD){
			audio = "Game/PaoDeKuai/Sound/Man/Man_zhadan";
		} else if (cardType === gameProto.cardType.FOUR_LINE_TAKE_ONE){
			audio = "Game/PaoDeKuai/Sound/Man/Man_sidaier";
		} else if (cardType === gameProto.cardType.FOUR_LINE_TAKE_TWO){
			audio = "Game/PaoDeKuai/Sound/Man/Man_sidailiangdui";
		}
		let user = this.roomUserInfoArr[chairID];
		if (user && user.userInfo.sex == 1) {
			audio = audio.replace(/Man/, "Woman");
			audio = audio.replace(/Man/, "Woman");
		}
		Global.AudioManager.playSound(audio);
	},

	playOutCardAnimation: function (cardDataArr, ctrl) {
		let cardType = gameLogic.getCardType(cardDataArr, this.gameRule);
		if (cardType === gameProto.cardType.BOMB_CARD){
			this.showZhadanAnimation();
		}
		else if (cardType === gameProto.cardType.THREE_LINE_TAKE_ONE){
			if (cardDataArr.length > 4){
				this.showFeijiAnimation();
			}
		}
		else if (cardType === gameProto.cardType.THREE_LINE_TAKE_TWO){
			if (cardDataArr.length > 5){
				this.showFeijiAnimation();
			}
		}
		else if (cardType === gameProto.cardType.SINGLE_LINE){
			this.showShunziAnimation(null, ctrl);
		}
		else if (cardType === gameProto.cardType.DOUBLE_LINE){
			this.showLianduiAnimation(null, ctrl);
		}
	},

	onUserPass: function (chairID, curChairID, isNewTurn, enablePass, handCardArr){
		let isPreOperate = true;
		// 显示pass状态
		let index = this.getUserChairIndex(chairID);
		if (chairID !== this.myChairID){
			isPreOperate = false;
			this.showTipNodeArr[index].getChildByName('pass').active = true;
		}
		else {
			let curCardArr = this.handCardWidgetCtrl.getAllCard();
			isPreOperate = (curCardArr.length == handCardArr.length);
			if (isPreOperate) {
				curCardArr.sort((a, b) => a-b);
				handCardArr.sort((a, b) => a-b);
				for (let i = 0; i < curCardArr.length && isPreOperate; ++i) {
					isPreOperate = (curCardArr[i] == handCardArr[i]);
				}
			}
			if (!isPreOperate) {
				let clockNode = this.operationBtnWidgetCtrl.getClockNode();
				if (!!clockNode) { // 停止计时器
					clockNode.destroyAllChildren();
				} 
				this.operationBtnWidgetCtrl.clearWidget(); // 隐藏按钮
				this.handCardWidgetCtrl.resetWidget();
				this.handCardWidgetCtrl.resetCardPos(); // 重置手牌位置
				this.handCardWidgetCtrl.resetSearchOutCardState();
				this.handCardWidgetCtrl.onSendCard(handCardArr, false);
				this.handCardWidgetCtrl.startGame();
			}
		}
		if (isNewTurn){
			this.turnCardDataArr = [];
		}
		// 删除定时器
		if (index !== 0){
			this.clockPosNodeArr[index].destroyAllChildren();
		}
		// 设置下一个出牌玩家
		if (curChairID >= 0) {
			this.onUserStartOutCard(curChairID, isNewTurn, enablePass);
		}

		let audio = "Game/PaoDeKuai/Sound/Man/Man_buyao1";
		let user = this.roomUserInfoArr[chairID];
		if (user && user.userInfo.sex == 1) {
			audio = audio.replace(/Man/, "Woman");
			audio = audio.replace(/Man/, "Woman");
		}
		Global.AudioManager.playSound(audio);
	},

	sendOutPass: function () {
		let clockNode = this.operationBtnWidgetCtrl.getClockNode();
		if (!!clockNode) { // 停止计时器
			clockNode.destroyAllChildren();
		} 
		this.operationBtnWidgetCtrl.clearWidget(); // 隐藏按钮
		this.handCardWidgetCtrl.resetCardPos(); // 重置手牌位置
		this.handCardWidgetCtrl.resetSearchOutCardState();

		let audio = "Game/PaoDeKuai/Sound/Man/Man_buyao1";
		let user = this.roomUserInfoArr[this.myChairID];
		if (user && user.userInfo.sex == 1) {
			audio = audio.replace(/Man/, "Woman");
			audio = audio.replace(/Man/, "Woman");
		}
		Global.AudioManager.playSound(audio);
	},


	onUserBombWin: function (chairID, isTween) {
		{ return; }
		for (let i = 0; i < 3; ++i){
			let index = this.getUserChairIndex(i);
			if (chairID === i){
				// 显示赢分动画
				if (isTween){
					this.winScoreLabelArr[index].node.active = true;
					this.winScoreLabelArr[index].string = "+" + Global.Utils.formatNumberToString(10, 2) + "元";
					this.winScoreLabelArr[index].node.position = cc.v2(0, -50);
					this.winScoreLabelArr[index].node.runAction(cc.sequence([cc.show(), cc.moveTo(0.2, cc.v2(0, 0)), cc.delayTime(2), cc.hide()]));
				}
				// 更新分数
				let goldCount = parseInt(this.goldLabelArr[index].string) + 10*this.gameRule.baseScore;
				this.goldLabelArr[index].string = Math.floor(goldCount);
			}else{
				// 显示输分动画
				if (isTween){
					this.loseScoreLabelArr[index].node.active = true;
					this.loseScoreLabelArr[index].string = Global.Utils.formatNumberToString(-5, 2) + "元";
					this.loseScoreLabelArr[index].node.position = cc.v2(0, -50);
					this.loseScoreLabelArr[index].node.runAction(cc.sequence([cc.show(), cc.moveTo(0.2, cc.v2(0, 0)), cc.delayTime(2), cc.hide()]));
				}
				// 更新分数
				let goldCount = parseFloat(this.goldLabelArr[index].string) - 5;
				this.goldLabelArr[index].string = Global.Utils.formatNumberToString(goldCount, 2);
			}

		}
	},

	onGameResult: function (resultData) {
		// 清除所有出牌
        /* for(let i = 0; i < 3; ++i){
            this.showOutCardNodeArr[i].removeAllChildren();
        } */
        // 隐藏警报
        for (let i = 1; i < 3; ++i){
            this.alertAnimationNodeArr[i].active = false;
        }
		// 隐藏状态
		for (let node of [this.showTipNodeArr[1], this.showTipNodeArr[2]]) {
			for (let child of node.children) {
				child.active = false;
			}
		}
		// 显示手牌
		for (let i = 0; i < 3; ++i){
			let index = this.getUserChairIndex(i);
			if (index === 0) continue;
			let cardArr = resultData.allCardArr[i];
			if (cardArr.length > 0 && this.roomUserInfoArr[i]){
				for (let j = 0; j < cardArr.length; j+=10){
					let node = cc.instantiate(this.showHandCardWidgetPrefab);
					let ctrl = node.getComponent('PDKShowHandCardWidgetCtrl');
					ctrl.initWidget(cardArr.slice(j, j + 10), index);
					node.parent = this.showHandCardNode[index];
				}
			}
		}
		if (resultData.hasChuntian) { /* 有春天 */ 
			let node = cc.instantiate(this.chuntianPrefab);
			node.parent = this.node;
			let animation = node.getComponent(cc.Animation);
			animation.play('chuntian');
			node.runAction(cc.sequence(
				cc.delayTime(2),
				cc.removeSelf()
			));
		}

		/* if (this.curBureau == this.gameRule.bureau) {
			this.updateUserInfo(); // 刷新用户信息
		}
		else {  */
			this.scheduleOnce(function () { // 显示结果
				let dialogParameters = { // 创建结束界面
					resultData: resultData,
					myChairID: this.myChairID,
					baseScore: 1,
					profitPercentage: 5,
					isBureauFull: (this.curBureau == this.gameRule.bureau),
					isDismissing: this.isDismissing.bind(this),
					pdkMainDialog: this,
				};
				Global.DialogManager.createDialog('Game/PaoDeKuai/PDKResultDialog', dialogParameters, function () {
					if (resultData.winChairID === this.myChairID){ // 播放音效
						Global.AudioManager.playSound("Game/PaoDeKuai/Sound/sound_win");
					}
					else {
						Global.AudioManager.playSound("Game/PaoDeKuai/Sound/sound_lose");
					}
				}.bind(this));
				cc.find('ready', this.node).active = true && (this.curBureau < this.gameRule.bureau);
				this.updateUserInfo(); // 刷新用户信息
			}.bind(this), (this.curBureau == this.gameRule.bureau)? 0:1);
		/* }  */
	},

	autoOutCard: function () {
		let autoCardArr = null;
		if (this.turnCardDataArr.length === 0){
			let handCardDataArr = this.handCardWidgetCtrl.getAllCard();
			if (!!gameLogic.getCardType(handCardDataArr, this.gameRule)) {
				autoCardArr = handCardDataArr.slice();
			} 
			else {
				autoCardArr = [handCardDataArr[handCardDataArr.length - 1]];
			}
		} 
		else {
			if (!!this.handCardWidgetCtrl.searchOutCard(this.turnCardDataArr, this.gameRule)) {
				autoCardArr = this.handCardWidgetCtrl.getSelectedCard();
			}
		}
		this.selfOutCardCallback(autoCardArr);
	},

	showClock: function (chairID, timeOutCallback) {
		let time = this.getIsFirstTurnByChairID(chairID)? 30:gameProto.OUT_CARD_TIME;
		let node = cc.instantiate(this.clockWidgetPrefab);
		let ctrl = node.getComponent('PDKClockWidgetCtrl');
		ctrl.isDismissing = this.isDismissing.bind(this);
		let index = this.getUserChairIndex(chairID);
		if (index === 0) {
			node.parent = this.operationBtnWidgetCtrl.getClockNode();
		}
		else {
			node.parent = this.clockPosNodeArr[index];
		}
		ctrl.startClock(time, (this.myChairID === chairID)?timeOutCallback:null);
	},

	updateCardCount: function (chairID, count) {
		if (chairID === this.myChairID) { return; }
		let index = this.getUserChairIndex(chairID);
		if (this.roomUserInfoArr[chairID]) {
			this.cardCountLabelArr[index].node.parent.active = true ;
			this.cardCountLabelArr[index].string = count.toString();
		}
		else {
			this.cardCountLabelArr[index].node.parent.active = false;
			this.cardCountLabelArr[index].string = count.toString();
		}
	},

	getUserChairIndex: function (chairID) {
		return (chairID - this.myChairID + 3)%3;
	},

	clearState: function (isRetainReady) {
		for (let i = 0; i < this.showTipNodeArr.length; ++i){
			let node = this.showTipNodeArr[i];
			for (let j = 0; j < node.children.length; ++j){
				if (isRetainReady && node.children[j].name === 'ready'){
					if (node.children[j].active) continue;
				}
				node.children[j].active = false;
			}
		}
	},

	// 动画
	// 发牌动画
	showSendCardAnimation: function () {
		this.cardNode.active = true;
		this.schedule(this.createCard, 0.1);
	},

	// 停止发牌动画
	stopSendCardAnimation: function () {
		this.cardNode.active = false;
		this.unschedule(this.createCard);
	},

	// 创建牌
	createCard: function() {
		let node0 = cc.instantiate(this.cardNode);
		node0.active = true;
		node0.parent = this.cardNode.parent;
		node0.runAction(cc.sequence([cc.moveBy(0.2, cc.v2(0, -300)), cc.removeSelf()]));

		if (this.roomUserInfoArr[(this.myChairID+1)%3]) {
			let node1 = cc.instantiate(this.cardNode);
			node1.active = true;
			node1.parent = this.cardNode.parent;
			node1.runAction(cc.sequence([cc.moveBy(0.2, cc.v2(400, -100)), cc.removeSelf()]));
		}

		if (this.roomUserInfoArr[(this.myChairID+2)%3]) {
			let node2 = cc.instantiate(this.cardNode);
			node2.active = true;
			node2.parent = this.cardNode.parent;
			node2.runAction(cc.sequence([cc.moveBy(0.2, cc.v2(-400, -100)), cc.removeSelf()]));
		}
	},

	// 顺子
	showShunziAnimation: function (pos, outCardCtrl) {
		if (!pos) pos = outCardCtrl.getCenterPos();
		let node = cc.instantiate(this.shunziAnimationPrefab);
		node.parent = this.animationNode;
		node.position = this.animationNode.convertToNodeSpaceAR(outCardCtrl.node.convertToWorldSpaceAR(pos));
		let ctrl = node.getComponent('SpriteFrameAnimationWidgetCtrl');
		ctrl.startAnimation(false, 1, function () {
			ctrl.node.removeFromParent();
		});

		let spriteNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/shunzi/shunzi');
		spriteNode.parent = node;
		spriteNode.x = -200;
		let moveAction = cc.moveTo(0.3,cc.v2(0,0));
		moveAction.easing(cc.easeOut(3));
		spriteNode.runAction(cc.sequence([moveAction, cc.fadeOut(0.4), cc.removeSelf()]));
	},

	// 连对
	showLianduiAnimation: function (pos, outCardCtrl) {
		if (!pos) pos = outCardCtrl.getCenterPos();
		let node = cc.instantiate(this.shunziAnimationPrefab);
		node.parent = this.animationNode;
		node.position = this.animationNode.convertToNodeSpaceAR(outCardCtrl.node.convertToWorldSpaceAR(pos));
		let ctrl = node.getComponent('SpriteFrameAnimationWidgetCtrl');
		ctrl.startAnimation(false, 1, function () {
			ctrl.node.removeFromParent();
		});

		let spriteNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/shunzi/liandui');
		spriteNode.parent = node;
		spriteNode.x = -200;
		let moveAction = cc.moveTo(0.3,cc.v2(0,0));
		moveAction.easing(cc.easeOut(3));
		spriteNode.runAction(cc.sequence([moveAction, cc.fadeOut(0.4), cc.removeSelf()]));
	},

	// 飞机
	showFeijiAnimation: function () {
		let feijiSpriteNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/feiji/1q');
		feijiSpriteNode.parent = this.animationNode;
		feijiSpriteNode.x = -800;
		feijiSpriteNode.y = 0;
		let moveAction1 = cc.moveTo(0.6, cc.v2(0, 0));
		moveAction1.easing(cc.easeOut(2));
		let moveAction2 = cc.moveTo(0.6, cc.v2(800, 0));
		moveAction2.easing(cc.easeIn(2));
		feijiSpriteNode.runAction(cc.sequence([moveAction1, moveAction2,cc.removeSelf()]));

		this.scheduleOnce(function () {
			let node = cc.instantiate(this.shunziAnimationPrefab);
			node.parent = this.animationNode;
			node.x = 0;
			node.y = -100;
			let ctrl = node.getComponent('SpriteFrameAnimationWidgetCtrl');
			ctrl.startAnimation(false, 1, function () {
				ctrl.node.removeFromParent();
			});

			let spriteNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/feiji/1w');
			spriteNode.parent = node;
			spriteNode.x = -200;
			spriteNode.y = 0;
			let moveAction = cc.moveTo(0.3,cc.v2(0,0));
			moveAction.easing(cc.easeOut(2));
			spriteNode.runAction(cc.sequence([moveAction, cc.fadeOut(0.4), cc.removeSelf()]));
		}.bind(this), 1);
	},

	// 炸弹
	showZhadanAnimation: function () {
		let spriteNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/zhadan/o');
		spriteNode.x = -200;
		spriteNode.parent = this.animationNode;
		spriteNode.runAction(cc.sequence([cc.jumpTo(0.3, cc.v2(0, 0), 100, 1), cc.callFunc(function () {
			let node = cc.instantiate(this.zhandanAnimationPrefab);
			node.parent = this.animationNode;
			let ctrl = node.getComponent('SpriteFrameAnimationWidgetCtrl');
			ctrl.startAnimation(false, 1, function () {
				ctrl.node.removeFromParent();
			});
			spriteNode.removeFromParent();

			let zhandanNode = Global.CCHelper.createSpriteNode('Game/PaoDeKuai/Animation/zhadan/1');
			zhandanNode.scale = 0.6;
			let action1 = cc.scaleTo(0.5, 1);
			action1.easing(cc.easeBackOut());
			zhandanNode.runAction(cc.sequence([action1, cc.delayTime(0.2), cc.fadeOut(0.3),cc.removeSelf()]));
			zhandanNode.parent = this.animationNode;
		}.bind(this))]));
	},

	onGameChat: function (chairID, type, msg) {
		let index = this.getUserChairIndex(chairID);
		let user = this.roomUserInfoArr[chairID];
		let node = this.msgTextNodeArr[index];
		let label = cc.find('Label', node);
		if (cc.find('emotion', node)) {
			cc.find('emotion', node).destroy();
		}
		if (type == 1) {
			label.active = false;
			let emotionNode = Global.CCHelper.getChatEmotionNode(msg, () => { node.active = false; });
			emotionNode.parent = node;
			emotionNode.setPosition(-70, 0);
			emotionNode.scaleX = node.scaleX;
			emotionNode.name = 'emotion';
			node.setContentSize(130, 110);
			node.active = true;
		}
		else if(type == 2) {
			let audioindex = ['快点啊，等到花儿都谢了！', '不要吵了，不要吵了。专心玩游戏吧！', '怎么又断线了，网络怎么这么差啊！', '不要走，决战到天亮！', '底牌亮出来绝对吓死你！', '风水轮流转，底裤都输光！', '看我通杀全场，这些钱都是我的！', '不好意思啊，我要离开一会！'].indexOf(msg);
			Global.AudioManager.playSound('Game/ChatAudio/' + ((user.userInfo.sex == 0)? 'man/':'woman/') +audioindex);
			label.getComponent(cc.Label).string = msg;
			this.scheduleOnce(() => {
				node.width = label.width+50;
				node.height = 58;
			}, 0);
			label.active = true;
			node.active = true;
			node.stopAllActions(); 
			node.runAction(cc.sequence(
				cc.delayTime(2),
				cc.callFunc(() => {
					node.active = false;
				})
			));
		}
	},


	onSwitchClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		let sprite = cc.find('Setting/bg/DismissButton/Sprite', this.node).getComponent(cc.Sprite);
		if (this.gameStarted) {
			Global.CCHelper.updateSpriteFrame('Game/Glob/dismiss', sprite);
		}
		else {
			Global.CCHelper.updateSpriteFrame('Game/Glob/leaveroom', sprite);
		}

		let bg = cc.find('Setting/bg', this.node);
		let url = 'Game/Glob/button1';
		let node = cc.find('Setting/Button/Background', this.node);
		if (!bg.active) {
			url = 'Game/Glob/button2';
			bg.active = true;
			Global.CCHelper.updateSpriteFrame(url, node.getComponent(cc.Sprite));
		}
		else {
			Global.CCHelper.updateSpriteFrame(url, node.getComponent(cc.Sprite));
			bg.active = false;
		}
	},

	onTrustClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		Global.NetworkManager.notify(GameMessageRouter, gameProto.gameTrushNotify(true));
	},

	onCancelTuoguan: function () {
		Global.AudioManager.playCommonSoundClickButton();
		Global.NetworkManager.notify(GameMessageRouter, gameProto.gameTrushNotify(false));
	},

	onSettingClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		Global.DialogManager.createDialog("UI/Setting/SettingDialog");
		this.onSwitchClick();
	},

	onRuleClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		let node = cc.find('Sprite/bg1/RuleButton', this.node);
		if (node.lastClick && Date.now()-node.lastClick < 500) { /* 防止重复点击 */ 
			return;
		}
		node.lastClick = Date.now();
		Global.DialogManager.createDialog('Game/RuleNode', this.getRule());
	},

	getRule: function () {
		let gameRule = this.gameRule;
		let rule = {
			'玩法：': ['', '经典玩法', '15张玩法', '平江玩法'][gameRule.gameFrameType] + (gameRule.showCardsCount? ' 显示牌数':' 不显示牌数') + (gameRule.fangzuobi? ' 防作弊':'') + (gameRule.heitao3? ' 首局出黑桃3':''),
			'出牌：': (gameRule.bichu? '必须出牌':'可不出牌'),
			'高级：': (gameRule.canTrust? '托管':'不托管') + (gameRule.fourTakeTwo? ' 允许4带2':'') + (gameRule.fourTakeThree? ' 允许4带3':'') + (gameRule.ThreeABomb? ' 三A算炸':'') + (gameRule.chaizhadan? ' 可拆炸弹':'不可拆炸弹') + (gameRule.hongtao10? ' 红桃10双倍':''),
		};
		return rule;
	},

	onExitClick: function (event, param) {
		Global.AudioManager.playCommonSoundClickButton();
		if (param != 'backhall') {
			this.onSwitchClick();
		}

		if (!this.gameStarted) {
			Global.DialogManager.addPopDialog('确认退出游戏?', function() {
				Global.NetworkManager.notify(RoomMessageRouter, roomProto.userLeaveRoomNotify());
				Global.DialogManager.addLoadingCircle();
			}, function() {});
		}
		else {
			Global.DialogManager.addPopDialog('是否确定发出解散申请？', function() {
				Global.NetworkManager.notify(RoomMessageRouter, roomProto.getAskForDismissNotifyData(true));
				Global.DialogManager.addLoadingCircle();
			}, function() {});
		} 
	},

	hasHeitao3: function (cards) {
		for (let card of cards) {
			if (card == 0x33) {
				return true;
			}
		}
		return false;
	},

	onReadyClick: function () {
		Global.AudioManager.playCommonSoundClickButton();
		this.onBtnClick(null, 'ready');
		cc.find('ready', this.node).active = false;
	},

	onCopyRoomID: function () {
		Global.AudioManager.playCommonSoundClickButton();
		let str = '跑得快---房间号：' + this.roomIDLabel.string.slice(3) + ' ';
		let rule = this.getRule();
		for (let key in rule) {
			str += key + rule[key] + ' ';
		}
		Global.PlatformHelper.copyText(str);
	},

	onInviteFriend: function () {
		Global.AudioManager.playCommonSoundClickButton();
		console.log('onInviteFriend');
	},

	onReview: function () {
		Global.AudioManager.playCommonSoundClickButton();
		Global.NetworkManager.notify(GameMessageRouter, gameProto.gamePreTurnCardsNotify());
	},

	getGameRule: function () {
		return this.gameRule || {};
	},

	onChat: function(fromChairID, toChairID, msg) {
		if (fromChairID == toChairID) {
			let url = 'Chat/vipEmoj/bailaoye/';
			let audio = 'Chat/ChatAnimSound/bailaoye_nan';
			let begin = 1, end = 11;
			if (msg == 22) {
				url = 'Chat/vipEmoj/caishen/';
				audio = 'Chat/ChatAnimSound/caishen_nan';
				begin = 1; end = 22;
			}
			else if (msg == 23) {
				url = 'Chat/vipEmoj/dajidali/';
				audio = 'Chat/ChatAnimSound/dajidali_nan';
				begin = 1; end = 23;
			}
			else if (msg == 24) {
				url = 'Chat/vipEmoj/haoqiyo/';
				audio = 'Chat/ChatAnimSound/haoqiyo_nan';
				begin = 1; end = 12;
			}
			else if (msg == 25) {
				url = 'Chat/vipEmoj/shengqile/';
				audio = 'Chat/ChatAnimSound/shengqile_nan';
				begin = 1; end = 8;
			}
			Global.AudioManager.playSound(audio);

			let node = new cc.Node();
			let sprite = node.addComponent(cc.Sprite);
			let animation = node.addComponent(cc.Animation);
			let urls = [];
			for (let i = begin; i <= end; ++i) {
				urls.push(url+i);
			}
			cc.loader.loadResArray(urls, cc.SpriteFrame, (err, frames) => {
				if (err) {
					console.log(urls, 'load error');
					return;
				}
				let clip = cc.AnimationClip.createWithSpriteFrames(frames, frames.length);
				clip.name = 'emotion';
				clip.speed = 0.5;
				animation.addClip(clip);
				animation.play('emotion');
				node.parent = this.node;
				node.runAction(cc.sequence(
					cc.delayTime(clip.duration+1),
					cc.removeSelf()
				));
			});
		}
		else {
			let node = cc.instantiate(this.chatAnim);
			node.parent = this.node;
			let logic = node.getComponent('ChatAnimal');
			logic.playAnimal(msg);
			let startIndex = this.getUserChairIndex(fromChairID);
			let startPos = cc.find('Head'+(startIndex+1), this.node).getPosition();
			let endIndex = this.getUserChairIndex(toChairID);
			let endPos = cc.find('Head'+(endIndex+1), this.node).getPosition();
			node.setPosition(startPos);
			node.runAction(cc.moveTo(0.5, endPos));
		}
	},

	onVoice: function () {
		Global.AudioManager.playCommonSoundClickButton();
		console.log('onVoice');
	},

	/*
	 * 首轮获取必须先出的牌
	 */
	getFirstOutCard: function (cards) {
		for (let i = 0x33; i <= 0x3C; ++i) {
			for (let j = i; j >= 0x01; j-=0x10) {
				for (let k = 0; k < cards.length; ++k) {
					if (cards[k] == j) {
						return cards[k];
					}
				}
			}
		}
		return null;
	},

	isDismissing: function () {
		return !!this.askForExitArr;
	},

	onRefrush: function (event) {
		if(!this.gameInited) { return; }
		if (event.target.lastClick && Date.now()-event.target.lastClick < 10*1000) {
			Global.DialogManager.addTipDialog('请勿频繁操作');
			return;
		}
		Global.DialogManager.addTipDialog('刷新界面可以修复游戏显示问题');
		event.target.lastClick = Date.now();
		Global.AudioManager.playCommonSoundClickButton();
		console.clash("paodekuai-onRefrush", this.getRoomData());
		this.messageCallbackHandler('ReConnectSuccess');
	},

	getIsFirstTurnByChairID: function (chairID) {
		return this.isFirstTurnArray[chairID];
	},

	setTwoPlayerHeadPos: function () {
		let head2 = cc.find('Head2', this.node);
		head2.setPosition(cc.v2(396, 205));
		// let showHandCardNode = cc.find('showHandCardNode', head2);
		// let showOutCardNode = cc.find('showOutCard', head2);
		// showHandCardNode.setPosition(showOutCardNode.getPosition());

		let head3 = cc.find('Head3', this.node);
		head3.setPosition(cc.v2(-396, 205));
		// showHandCardNode = cc.find('showHandCardNode', head3);
		// showOutCardNode = cc.find('showOutCard', head3);
		// showHandCardNode.setPosition(showOutCardNode.getPosition());
	},

	setBanker: function (chairID) {
		let index = this.getUserChairIndex(chairID);
		for (let i = 0; i < 3; ++i) {
			let bankNode = cc.find("Head"+(i+1)+"/banker", this.node);
			bankNode.active = (i == index);
		}
	},

});
